import Vue from 'vue'
import VueI18n from 'vue-i18n'
import buildConfig from 'src/buildConfig.json'

Vue.use(VueI18n);
let I18n = new VueI18n({
  locale: '',
  messages: {}
});

export default I18n;

const loadedLanguages = [];

export function setI18nLanguage(lang: string) {
  I18n.locale = lang;
  (<any>document).title = I18n.t("header.siteTitle");

  return lang
}

export function loadLanguageAsync(lang: string) {
  if (I18n.locale !== lang) {
    if (!loadedLanguages.includes(lang)) {
      return fetch(`${buildConfig.publicPath}languages/${lang}.json`).then(res => res.json()).then(msgs => {
        I18n.setLocaleMessage(lang, {
          ...msgs
        });
        loadedLanguages.push(lang);

        return setI18nLanguage(lang)
      })
    }

    return Promise.resolve(setI18nLanguage(lang))
  }

  return Promise.resolve(lang)
}

loadLanguageAsync('zh-CN');
